$(document).ready(function(){
    var emails = [];
    function pushEmail(name) {
        var flag = isEmail(name);
        if (flag) {
            emails.push(name);
        }

//        if (flag) {
//            if ($.inArray(name, emails)) {
//                emails.push(name);
//                flag = true;
//            } else {
//                // T0DO
//                flag = false;
//            }
//        }
        return flag;
    }

    function isEmail(email){
        var flag = false;
        // Trim space
        email = $.trim(email);
        var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        flag =  regex.test(email);
        return flag;
    }

    $.fn.invite_friends = function(options){
        $(this).click(function(){
            FB.getLoginStatus(function(response) {
            FB.login(function(response) {
            var id_user = response.authResponse.userID;
            FB.api('/' + id_user, {fields:"id, name, picture"}, function(response){
                Social.getDialog().create({
                    title: options['title'],
                    content: options['template'],
                    closeIcon: true,
                    minWidth: 650,
                    buttons:{
                        'Send': function() {
                            var flag = true;
                            var iemail = $.trim($('#iemail').val());
                            if (iemail != '') {
                                if (!isEmail(iemail)) {
                                    $('.fac-error').html("Invalid email");
                                    flag = false;
                                } else {
                                    emails.push(iemail);
                                    flag = true;
                                }
                            }
                            if (flag && (emails.length == 0)) {
                               $('.fac-error').html("Value is required and can't be empty");
                               flag = false;
                            }
                            if ($.trim( $('#email_subject').val()) == "") {
                                $('.fac-error-subject').html("Value is required and can't be empty");
                                flag = false;
                            }
                            if ($.trim($('#ms_content').val()) == "") {
                                $('.fac-error-message').html("Value is required and can't be empty");
                                flag = false;
                            }
                            if (flag){
                                $.post(options['url'], {
                                   'recipients[]': emails,
                                   subject: $('#email_subject').val(),
                                   content: $('#ms_content').val()
                                }, function(data){
                                }, "json");
                                emails = [];
                                $(this).dialog("destroy");
                            }
                        },
                        'Close': function(){
                            $(this).dialog("destroy");
                        }
                    },
                    init: function(){
                        var iemail = {
                            lindex: 10,
                            ldefault: 50,
                            lmargin: 30
                        }
                        var subject = $('#email_subject').val();
                        subject = subject.replace('%fb_name%', response.name);

                        if (options['is_contest'] == '1') {
                            subject += ' contest';
                            subject = subject.replace('%join%', 'join');
                        } else {
                            subject = subject.replace('%join%', 'vote');
                        }
                        $('#email_subject').val(subject);
                        $('#iemail').keypress(function(e) {
                            switch (e.keyCode) {
                                case 44:
                                case 13: // Enter
                                    var email = $(this).val();
                                    if (pushEmail(email)) {
                                        //TODO: check email
                                        var span = '<span class="email">'+
                                                    $.trim($('#iemail').val())+
                                                    '<a href="#" class="uiCloseButton"></a>'
                                                    '</span>';
                                        $('#iemail').before(span);
                                        $('.uiCloseButton').click(function(){
                                            $(this).parent().remove();
                                        });
                                        // Empty input
                                        $(this).val('');
                                        e.preventDefault();

                                        // Remove errors
                                        $('.fac-error').html('');
                                    } else {
                                        var iemail = $.trim($('#iemail').val());
                                        if (iemail != '') {
                                            $('.fac-error').html('Invalid email');                                            
                                        }                                        
                                    }
                                    break;
                                default:
                                    var text = $('#iemail').val();
                                    var l = parseInt(text.length)*iemail.lindex + iemail.lmargin;
                                    $('#iemail').width(l);
                                    $('#iemail').attr('l', text.length);
                                    break;
                            }
                        });//iemail keypress

                        $('#iemail').keyup(function(event) {
                            switch(event.keyCode) {
                                case 8:
                                case 46:
                                    var l = parseInt($('#iemail').attr('l'));
                                    if (l == 0) {
                                        // Delete previous email
                                        $('.email:last').remove();
                                        if (!$('.email:first').val()) {
                                            emails = [];
                                        }
                                    } else {
                                        // Resize width
                                        var text = $('#iemail').val();
                                        $('#iemail').attr('l', text.length);
                                        var dl  = (text.length - l)*iemail.lindex;
                                        var delta = $('#iemail').width() - dl;
                                        console.log(delta);
                                        if (delta < iemail.ldefault) {
                                            $('#iemail').width(iemail.ldefault);
                                        } else {
                                            $('#iemail').width(dl + iemail.lmargin);
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                        });// iemail keyup

                        // Frame
                        $('.fac-frame').click(function(){
                            $('#iemail').focus();
                        });

                        var content = options.content;
                        content = content.replace('%fb_name%', response.name);
                        if (options['is_contest'] == '1') {
                            content = content.replace(/%contest%/g, 'contest');
                            content = content.replace(/%join%/g, 'join');
                        } else {
                            content = content.replace(/%contest%/g, 'entry');
                            content = content.replace(/%join%/g, 'vote');
                        }
                        setTimeout(function(){
                            $('#ms_content').val(content);
                        }, 1000);

                        jQuery("#ms_content").tinymce({
                            script_url : "/contest/public/media/vendor/tiny_mce/tiny_mce_min.js",
                            content_css : "/contest/public/media/style/tinymce.css",
                            mode : "textareas",
                            theme : "advanced",
                            entity_encoding : "raw",
                            convert_urls : "",
                            valid_elements : "*[*]",
                            extended_valid_elements : "a[href|target:_blank]",
                            theme_advanced_toolbar_location : "top",
                            theme_advanced_toolbar_align : "left",
                            theme_advanced_statusbar_location : "bottom",
                            theme_advanced_blockformats : "p,address,h1,h2,h3,h4,h5,h6",
                            width : "500",
                            skin : "o2k7",
                            plugins : "autolink,safari,advimage,emotions,media,style,fullscreen",
                            theme_advanced_buttons1 : "undo,redo,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
                            theme_advanced_buttons2 : "forecolor,backcolor,|,bullist,numlist,|,sub,sup,|,outdent,indent,blockquote,|,link,unlink,image,cleanup,|,charmap,emotions,media,|,removeformat,styleprops,fullscreen,code",
                            theme_advanced_buttons3 : "",
                            theme_advanced_resizing : "1",
                            skin_variant : "silver",
                            theme_advanced_resize_horizontal : "",
                            theme_advanced_resizing_use_cookie : "0"
                        });

                }
            });

            });

                });
            });

        });
    };
});